﻿using System;
using System.Collections.Specialized;
using System.Configuration;
using System.Drawing;
using System.IO;
using System.Net;
using System.Threading;

namespace GetWallPagerFromBing
{
    class Program
    {
        static void Main(string[] args)
        {
            bool isConnected = Utils.IsConnectNetwork();

            if (isConnected)
            {
                Run();
            }
            else
            {
                //没联网怎么办
                SimpleLog.GetLog("还没有联网，不能获取图片哦");

                while (!isConnected)
                {
                    Thread.Sleep(1000 * 60 * 5);
                    isConnected = Utils.IsConnectNetwork();
                }

                Run();
            }

            RegistryKeyOption.SetStartAfterPowerOn();
        }

        private static void Run()
        {
            NameValueCollection nv = ConfigurationManager.AppSettings;

            if (nv.Count > 0)
            {
                if (!string.IsNullOrEmpty(nv["bingUrl"]))
                {
                    WebRequest request = WebRequest.Create(new Uri(nv["bingUrl"]));
                    request.Method = "GET";

                    try
                    {
                        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                        SimpleLog.GetLog("发起获取json请求");

                        using (Stream stream = response.GetResponseStream())
                        {
                            SimpleLog.GetLog("获得json数据");
                            using (StreamReader sr = new StreamReader(stream))
                            {
                                string result = sr.ReadToEnd();

                                BingObject bingObject = Newtonsoft.Json.JsonConvert.DeserializeObject<BingObject>(result);

                                if (bingObject != null)
                                {
                                    if (bingObject.Images.Length > 0)
                                    {
                                        string imageUrl = bingObject.Images[0].url;

                                        if (!string.IsNullOrEmpty(imageUrl))
                                        {
                                            WebRequest fw = FileWebRequest.Create(imageUrl);
                                            fw.Method = "GET";

                                            SimpleLog.GetLog("发起获取图片请求");
                                            WebResponse fileResponse = fw.GetResponse();

                                            using (Stream fileStream = fileResponse.GetResponseStream())
                                            {
                                                string path = Path.Combine(Utils.AppPath, "bingMap.jpg");

                                                using (FileStream fs = File.Create(path))
                                                {
                                                    using (MemoryStream ms = new MemoryStream())
                                                    {
                                                        fileStream.CopyTo(ms);

                                                        fs.Write(ms.ToArray(), 0, Convert.ToInt32(ms.Length));
                                                    }
                                                }

                                                SimpleLog.GetLog("获得图片并且保存成功");

                                                if (File.Exists(path))
                                                {
                                                    string bitMap = Path.Combine(Utils.AppPath, "realBG.bmp");

                                                    using (Image image = Image.FromFile(path))
                                                    {
                                                        image.Save(bitMap, System.Drawing.Imaging.ImageFormat.Bmp);
                                                    }

                                                    if (File.Exists(bitMap))
                                                    {
                                                        bool result_BG = Win32Util.SystemParametersInfo(20, 0, bitMap, 1);

                                                        if (result_BG)
                                                        {
                                                            SimpleLog.GetLog("设置完成");

                                                            File.Delete(bitMap);

                                                            File.Delete(path);
                                                        }
                                                        else
                                                        {
                                                            int errorCode = Win32Util.GetLastError();
                                                            SimpleLog.GetLog("设置失败;错误代码" + errorCode);
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        SimpleLog.GetLog(e.Message);
                    }
                }
            }
        }
    }
}
